import redis
import os
from typing import Optional

# Redis配置
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
REDIS_DB = int(os.getenv("REDIS_DB", "0"))
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", None)

# 创建Redis连接池
try:
    redis_pool = redis.ConnectionPool(
        host=REDIS_HOST,
        port=REDIS_PORT,
        db=REDIS_DB,
        password=REDIS_PASSWORD,
        decode_responses=True,
        max_connections=20
    )
    
    # 创建Redis客户端
    redis_client = redis.Redis(connection_pool=redis_pool)
    
    # 测试连接
    redis_client.ping()
    print("Redis连接成功")
except Exception as e:
    print(f"Redis连接失败: {e}")
    print("将使用内存缓存替代Redis")
    redis_client = None

# Redis键名常量
class RedisKeys:
    # 验证码相关
    VERIFY_CODE = "verify_code:{phone}"  # 验证码缓存，过期时间5分钟
    CODE_LIMIT = "code_limit:{phone}"    # 发送限制，过期时间60秒
    
    # 登录安全相关
    LOGIN_FAIL = "login_fail:{phone}"    # 登录失败计数，过期时间5分钟
    LOGIN_LOCK = "login_lock:{phone}"    # 登录锁定，过期时间5分钟
    USER_TOKEN = "user_token:{user_id}"  # 用户Token，无过期时间

# Redis工具函数
class RedisUtils:
    @staticmethod
    def _check_connection():
        """检查Redis连接"""
        if redis_client is None:
            raise Exception("Redis连接不可用")
    
    @staticmethod
    def set_with_expire(key: str, value: str, expire_seconds: int) -> bool:
        """设置键值并指定过期时间"""
        RedisUtils._check_connection()
        return redis_client.setex(key, expire_seconds, value)
    
    @staticmethod
    def get(key: str) -> Optional[str]:
        """获取键值"""
        RedisUtils._check_connection()
        return redis_client.get(key)
    
    @staticmethod
    def delete(key: str) -> bool:
        """删除键"""
        RedisUtils._check_connection()
        return bool(redis_client.delete(key))
    
    @staticmethod
    def exists(key: str) -> bool:
        """检查键是否存在"""
        RedisUtils._check_connection()
        return bool(redis_client.exists(key))
    
    @staticmethod
    def incr(key: str, expire_seconds: int = None) -> int:
        """自增并设置过期时间"""
        RedisUtils._check_connection()
        result = redis_client.incr(key)
        if expire_seconds and result == 1:  # 第一次创建时设置过期时间
            redis_client.expire(key, expire_seconds)
        return result
    
    @staticmethod
    def set(key: str, value: str, expire_seconds: int = None) -> bool:
        """设置键值"""
        RedisUtils._check_connection()
        if expire_seconds:
            return redis_client.setex(key, expire_seconds, value)
        return redis_client.set(key, value)
